package com.link.base.base.wechat.service;

import com.link.base.base.wechat.dao.mybatis.mapper.MessageresultMapper;
import com.link.base.base.wechat.model.Messageresult;
import com.link.base.base.wechat.model.MpnewsTimer;
import com.link.base.wechat.wxmessage.model.WxMessage;
import com.link.base.wechat.wxmessage.service.WxMessageService;
import com.link.base.wechat.wxplatform.model.WxPlatform;
import com.link.base.wechat.wxplatform.service.WxPlatformService;
import com.link.base.wechat.wxsubscriber.model.Subscriber;
import com.link.base.wechat.wxsubscriber.service.WxSubscriberService;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.basic.service.ServiceException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 消息发送接口实现类
 *
 * @author lujiang
 * @date 2018-05
 */
@Service
public class MessageresultServiceImpl extends BasicServiceImpl<Messageresult> implements MessageresultService {
    @Resource
    private WxPlatformService wxPlatformService;
    @Resource
    private MessageresultMapper messageresultMapper;
    @Resource
    private WxSubscriberService wxSubscriberService;
    @Resource
    private SendToAllFollowersService sendToAllFollowersService;
    @Resource
    private WxMessageService wxMessageService;


    @Override
    public BasicMapper<Messageresult> getBasicMapper() {
        return messageresultMapper;
    }


    @Override
    public String allSendMpnews(Long mediaId, WxPlatform platform, String time) throws Exception {
        String mes = "fail";
        Subscriber entity = new Subscriber();
        entity.setLoginCorpId(platform.getLoginCorpId());
        entity.setOgId(platform.getWx_og_id());
        entity.setPageFlag(false);
        String imediately = "Imediately";
        List<Subscriber> subscribers = wxSubscriberService.queryByExamplePage(entity);
        if (null == time || (imediately).equals(time)) {
            //立即发送
            Map<String, Object> resultmap = new HashMap<>(16);
            Map<String, Object> jsonmap = new HashMap<>(16);
            // 查出来的openid
            List<String> lista = new ArrayList<>();
            for (int i = 0; i < subscribers.size(); i++) {
                String openid = subscribers.get(i).getOpenid();
                lista.add(openid);
            }
            WxMessage wxMessage = new WxMessage();
            wxMessage.setMsgType("mpnews");
            wxMessage.setContents(String.valueOf(mediaId));
            wxMessage.setOpenIds(lista);
            int num = wxMessageService.sendMsg(wxMessage,platform.getWx_app_id());
            for (int i = 0; i < subscribers.size(); i++) {
                Messageresult result = new Messageresult();
                result.setContent(String.valueOf(mediaId));
                result.setContentType("mpnews");
                result.setTouser(subscribers.get(i).getOpenid());
                result.setWxId(String.valueOf(platform.getId()));
                result.setDate(time);
                if (num == 1) {
                    result.setStatus("Succeeded");
                } else {
                    result.setStatus("Failed");
                }
                result.setType("MPNews");
                result.setFromUser(platform.getWx_og_id());
                result.setOpenid(subscribers.get(i).getOpenid());
                result.setWxusername(platform.getWx_og_id());
                insert(result);
            }
            if (num == 1) {
                mes = "success";
            }
        } else {
            //定时发送，先存规则，再存记录。
            MpnewsTimer allFollowers = new MpnewsTimer();
            allFollowers.setWxId(String.valueOf(platform.getId()));
            allFollowers.setSendTime(time);
            allFollowers.setMediaId(mediaId);
            allFollowers.setContenType("mpnews");
            sendToAllFollowersService.insert(allFollowers);
            for (int i = 0; i < subscribers.size(); i++) {
                //消息记录表存储，做定时任务
                Messageresult result = new Messageresult();
                result.setContent(String.valueOf(mediaId));
                result.setContentType("mpnews");
                result.setTouser(subscribers.get(i).getOpenid());
                result.setWxId(String.valueOf(platform.getId()));
                result.setDate(time);
                result.setStatus("New");
                result.setType("MPNews");
                result.setFromUser(platform.getWx_og_id());
                result.setSendId(allFollowers.getId());
                result.setOpenid(subscribers.get(i).getOpenid());
                result.setWxusername(platform.getWx_og_id());
                //插入
                insert(result);
            }
            mes = "success";
        }
        return mes;
    }

    @Override
    public Map<String, Object> nowSend(List<Messageresult> list) throws Exception {
        Map<String, Object> map = new HashMap<>(16);
        if (list.size() < 1) {
            throw new ServiceException("WECHAT-011");
        }
        WxPlatform wxPlatform = new WxPlatform();
        wxPlatform.setId(Long.valueOf(list.get(0).getWxId()));
        WxPlatform platform = wxPlatformService.queryById(wxPlatform);
        for (int i = 0; i < list.size(); i++) {
            Messageresult messageresult = list.get(i);
            this.insert(messageresult);
            WxMessage message = new WxMessage();
            message.setContents(messageresult.getContent());
            message.setMsgType(messageresult.getContentType());
            message.setAppid(platform.getWx_app_id());
            message.setFromUserName(messageresult.getTouser());
            int result = wxMessageService.wxSendMsg(message,wxPlatform.getWx_app_id());
            if (result == 1) {
                messageresult.setStatus("Succeeded");
            }
            this.update(list.get(i));
        }
        return map;
    }
}
